﻿/******************************************************************************
 *  All Rights Reserved , Copyright (C) 2012 , EricHu. 
 *  作    者： EricHu
 *  创建时间： 2012-5-12 10:15:58
 ******************************************************************************/
using System;
using System.Data;
using System.Reflection;
using System.ServiceModel;

namespace RDIFramework.ServiceAdapter
{
    using RDIFramework.BusinessEntity;
    using RDIFramework.IService;
	using RDIFramework.Utilities;

	/// <summary>
    /// PermissionService
    /// 权限判断服务
	/// 
	/// 修改记录
	/// 
	///		2012-05-12 版本：1.0 EricHu 建立。
	///		
	/// 版本：1.0
	///
	/// <author>
	///		<name>EricHu</name>
	///		<date>2012-05-12</date>
	/// </author> 
	/// </summary>
	[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
	public partial class PermissionService : System.MarshalByRefObject, IPermissionService
	{
        private readonly string serviceName = RDIFrameworkMessage.PermissionService;

        /// <summary>
        /// .NET快速开发整合框架（RDIFramework.NET）数据库连接
        /// </summary>
        private readonly string RDIFrameworkDbConection = SystemInfo.RDIFrameworkDbConection;

        //////////////////////////////////////////////////////////////////////////////////////////////////////
        /// 用户权限判断相关(需要实现对外调用)
        //////////////////////////////////////////////////////////////////////////////////////////////////////

        #region public bool IsInRole(UserInfo userInfo, string userId, string roleName) 指定用户是否在指定的角色里
        /// <summary>
        /// 指定用户是否在指定的角色里
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="UserId">用户主键</param>
        /// <param name="roleName">角色名称</param>
        /// <returns>指定用户是否在指定角色里，true：是，false：否</returns>
        public bool IsInRole(UserInfo userInfo, string userId, string roleName)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 先获得角色主键
                    PiRoleManager roleManager = new PiRoleManager(dbProvider, userInfo);
                    string roleCode = roleManager.GetProperty(PiRoleTable.FieldRealName, roleName, PiRoleTable.FieldCode);
                    // 判断用户的默认角色
                    if (!string.IsNullOrEmpty(roleCode))
                    {
                        PiUserRoleManager userRoleManager = new PiUserRoleManager(dbProvider, userInfo);
                        returnValue = userRoleManager.UserInRole(userId, roleCode);
                    }
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsInRole, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public bool IsAuthorized(UserInfo userInfo, string permissionItemCode, string permissionItemName = null) 当前用户是否有相应的权限
        /// <summary>
        /// 当前用户是否有相应的权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="permissionItemCode">权限编号</param>
        /// <param name="permissionItemName">权限名称</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsAuthorized(UserInfo userInfo, string permissionItemCode, string permissionItemName = null)
        {
            return IsAuthorizedByUserId(userInfo, userInfo.Id, permissionItemCode, permissionItemName);
        }
        #endregion

        #region public bool IsAuthorizedByUserId(UserInfo userInfo, string userId, string permissionItemCode, string permissionItemName = null) 指定用户是否有相应的操作权限
        /// <summary>
        /// 指定用户是否有相应的操作权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <param name="permissionItemCode">权限编号</param>
        /// <param name="permissionItemName">权限名称</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsAuthorizedByUserId(UserInfo userInfo, string userId, string permissionItemCode, string permissionItemName = null)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);

                    if (string.IsNullOrEmpty(userId))
                    {
                        userId = userInfo.Id;
                    }

                    #if (!DEBUG)
                    // 是超级管理员,就不用继续判断权限了
                    PiUserManager userManager = new PiUserManager(dbProvider, userInfo);
                    returnValue = userManager.IsAdministrator(userId);
                    if (returnValue)
                    {
                        return returnValue;
                    }
                    #endif
                    
                    PiPermissionManager permissionManager = new PiPermissionManager(dbProvider, userInfo);
                    returnValue = permissionManager.CheckPermissionByUser(userId, permissionItemCode, permissionItemName);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsAuthorizedByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public bool IsAuthorizedByRoleId(UserInfo userInfo, string roleId, string permissionItemCode) 指定角色是否有相应的权限
        /// <summary>
        /// 指定角色是否有相应的权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="roleId">角色主键</param>
        /// <param name="permissionItemCode">权限编号</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsAuthorizedByRoleId(UserInfo userInfo, string roleId, string permissionItemCode)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 是超级管理员,就不用继续判断权限了
                    returnValue = roleId.Equals("Administrators");
                    if (returnValue)
                    {
                        return returnValue;
                    }
                    PiPermissionManager permissionManager = new PiPermissionManager(dbProvider, userInfo);
                    returnValue = permissionManager.CheckPermissionByRole(roleId, permissionItemCode);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsAuthorizedByRoleId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public bool IsAdministrator(UserInfo userInfo) 当前用户是否超级管理员
        /// <summary>
        /// 当前用户是否超级管理员
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>当前用户是否为超级管理员，true：是，false：否</returns>
        public bool IsAdministrator(UserInfo userInfo)
        {
            return IsAdministratorByUserId(userInfo, userInfo.Id);
        }
        #endregion

        #region public bool IsAdministratorByUserId(UserInfo userInfo, string userId) 指定用户是否超级管理员
        /// <summary>
        /// 指定用户是否超级管理员
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <returns>是否超级管理员，true：是，false：否</returns>
        public bool IsAdministratorByUserId(UserInfo userInfo, string userId)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    PiUserManager userManager = new PiUserManager(dbProvider, userInfo);
                    returnValue = userManager.IsAdministrator(userId);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsAdministratorByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public DataTable GetPermissionDT(UserInfo userInfo) 获得当前用户的所有权限列表
        /// <summary>
        /// 获得当前用户的所有权限列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <returns>权限数据表</returns>
        public DataTable GetPermissionDT(UserInfo userInfo)
        {
            return GetPermissionDTByUserId(userInfo, userInfo.Id);
        }
        #endregion

        #region public DataTable GetPermissionDTByUserId(UserInfo userInfo, string userId) 获得指定用户的所有权限列表
        /// <summary>
        /// 获得指定用户的所有权限列表
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <returns>权限数据表</returns>
        public DataTable GetPermissionDTByUserId(UserInfo userInfo, string userId)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            DataTable dataTable = new DataTable(PiPermissionItemTable.TableName);
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 是否超级管理员
                    PiUserManager userManager = new PiUserManager(dbProvider, userInfo);
                    if (userManager.IsAdministrator(userId))
                    {
                        PiPermissionItemManager permissionAdminManager = new PiPermissionItemManager(dbProvider, userInfo);
                        dataTable = permissionAdminManager.GetDT();
                    }
                    else
                    {
                        PiPermissionManager permissionManager = new PiPermissionManager(dbProvider);
                        dataTable = permissionManager.GetPermissionByUser(userId);
                    }
                    dataTable.TableName = PiPermissionItemTable.TableName;
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_GetPermissionDTByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return dataTable;
        }
        #endregion     

        #region public bool IsModuleAuthorized(UserInfo userInfo, string moduleCode) 当前用户是否对某个模块有相应的权限
        /// <summary>
        /// 当前用户是否对某个模块有相应的权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="moduleCode">模块编号</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsModuleAuthorized(UserInfo userInfo, string moduleCode)
        {
            return IsModuleAuthorizedByUserId(userInfo, userInfo.Id, moduleCode);
        }
        #endregion

        #region public bool IsModuleAuthorizedByUserId(UserInfo userInfo, string userId, string moduleCode) 指定用户是否对某个模块有相应的权限
        /// <summary>
        /// 指定用户是否对某个模块有相应的权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <param name="moduleCode">模块编号</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsModuleAuthorizedByUserId(UserInfo userInfo, string userId, string moduleCode)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 是否超级管理员
                    PiUserManager userManager = new PiUserManager(dbProvider, userInfo);
                    if (userManager.IsAdministrator(userId))
                    {
                        return true;
                    }
                    else
                    {
                        PiModuleManager moduleManager = new PiModuleManager(dbProvider, userInfo);
                        DataTable dataTable = moduleManager.GetDTByUser(userId);
                        foreach (DataRow dataRow in dataTable.Rows)
                        {
                            if (dataRow[PiModuleTable.FieldCode].ToString().Equals(moduleCode))
                            {
                                returnValue = true;
                                break;
                            }
                        }
                    }
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsModuleAuthorizedByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public bool IsModuleAuthorizedByUserId(UserInfo userInfo, string userId, string moduleCode, string permissionItemCode) 某个用户是否对某个模块有相应的权限
        /// <summary>
        /// 某个用户是否对某个模块有相应的权限
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <param name="moduleCode">模块编号</param>
        /// <returns>是否有权限，true：是，false：否</returns>
        public bool IsModuleAuthorizedByUserId(UserInfo userInfo, string userId, string moduleCode, string permissionItemCode)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            bool returnValue = false;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 是超级管理员,就不用继续判断权限了
                    PiUserManager userManager = new PiUserManager(dbProvider, userInfo);
                    returnValue = userManager.IsAdministrator(userId);
                    if (returnValue)
                    {
                        return returnValue;
                    }
                    PiPermissionScopeManager permissionScopeManager = new PiPermissionScopeManager(dbProvider);
                    returnValue = permissionScopeManager.IsModuleAuthorized(userId, moduleCode, permissionItemCode);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_IsModuleAuthorizedByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion

        #region public PermissionScope GetPermissionScopeByUserId(UserInfo userInfo, string userId, string permissionItemCode) 获得指定用户的数据权限范围
        /// <summary>
        /// 获得指定用户的数据权限范围
        /// </summary>
        /// <param name="userInfo">用户</param>
        /// <param name="userId">用户主键</param>
        /// <param name="permissionItemCode">数据权限编号</param>
        /// <returns>数据权限范围</returns>
        public PermissionScope GetPermissionScopeByUserId(UserInfo userInfo, string userId, string permissionItemCode)
        {
            // 写入调试信息
            #if (DEBUG)
            int milliStart = BusinessLogic.StartDebug(userInfo, MethodBase.GetCurrentMethod());
            #endif

            // 加强安全验证防止未授权匿名调用
            #if (!DEBUG)
                LogOnService.UserIsLogOn(userInfo);
            #endif

            PermissionScope returnValue = PermissionScope.None;
            using (IDbProvider dbProvider = DbFactoryProvider.GetProvider(SystemInfo.RDIFrameworkDbType))
            {
                try
                {
                    dbProvider.Open(RDIFrameworkDbConection);
                    // 是超级管理员,就不用继续判断权限了
                    PiPermissionScopeManager permissionScopeManager = new PiPermissionScopeManager(dbProvider, userInfo);
                    returnValue = permissionScopeManager.GetUserPermissionScope(userId, permissionItemCode);
                    LogManager.Instance.Add(dbProvider, userInfo, this.serviceName, RDIFrameworkMessage.PermissionService_GetPermissionScopeByUserId, MethodBase.GetCurrentMethod());
                }
                catch (Exception ex)
                {
                    CiExceptionManager.LogException(dbProvider, userInfo, ex);
                    throw ex;
                }
                finally
                {
                    dbProvider.Close();
                }
            }

            // 写入调试信息
            #if (DEBUG)
            BusinessLogic.EndDebug(MethodBase.GetCurrentMethod(), milliStart);
            #endif

            return returnValue;
        }
        #endregion
	}
}
